package com.corechina.apex_osswords.common;

import com.alibaba.fastjson.JSONObject;
import com.corechina.apex_osswords.common.config.WeiXinConfig;
import com.corechina.apex_osswords.domain.vo.AccessTokenVo;
import com.corechina.apex_osswords.service.IRedisService;
import com.corechina.apex_osswords.service.impl.RedisServiceImpl;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.TreeMap;

public class WeiXinUtil {
    private static Logger log = LoggerFactory.getLogger(WeiXinUtil.class);

    /**
     * 获取access_token
     *
     * @param appid     凭证
     * @param appsecret 密钥
     * @return
     */
    public static AccessTokenVo getAccessToken(String appid, String appsecret) {
        AccessTokenVo accessTokenVo = null;
        TreeMap<String, Object> params = new TreeMap<>();
        params.put("grant_type", "client_credential");
        params.put("appid", WeiXinConfig.APP_ID);
        params.put("secret",WeiXinConfig.APP_SECRET);

        String result = HttpUtil.get(WeiXinConfig.ACCESS_TOKEN_URL, params, null);
        JSONObject jsonObject = JSONObject.parseObject(result);
        // 如果请求成功
        if (null != jsonObject) {
            try {
                accessTokenVo = new AccessTokenVo();
                accessTokenVo.setToken(jsonObject.getString("access_token"));
                accessTokenVo.setExpiresIn(jsonObject.getInteger("expires_in"));
            } catch (Exception e) {
                accessTokenVo = null;
                // 获取token失败
                log.error("获取token失败 errcode:{} errmsg:{}", jsonObject.getInteger("errcode"), jsonObject.getString("errmsg"));
            }
        }
        return accessTokenVo;
    }

}